package com.konsung.util;

import android.content.Context;
import android.text.TextUtils;
import android.util.Base64;

import com.konsung.bean.MeasureDataBean;
import com.konsung.bean.PatientBean;
import com.konsung.greendaoUtil.GreenDaoManager;
import com.konsung.greendaoUtil.MeasureDataBeanDao;
import com.konsung.greendaoUtil.PatientBeanDao;
import com.konsung.provide.ProviderReader;
import com.konsung.util.constant.GlobalConstant;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 数据处理的类
 */
public class DBDataUtil {

    /**
     * @return 模板的xml文件
     */
    public static String getUpLoadXml() {
        String str = "<TAIO_HEACHECK>" +
                "<id>%s</id>" +
                "<uploadDate>%s</uploadDate>" +
                "<area>%s</area>" +
                "<equipmentModel>%s</equipmentModel>" +
                "<key>%s</key>" +
                "<IcpName>%s</IcpName>" +
                "<DeviceID>%s</DeviceID>" +
                "<CardNo>%s</CardNo>" +
                "<Name>%s</Name>" +
                "<Sex>%s</Sex>" +
                "<Birthday>%s</Birthday>" +
                "<Doctor>%s</Doctor>" +
                "<CheckDate>%s</CheckDate>" +
                "<HR>%s</HR>" +
                "<SBP>%s</SBP>" +
                "<DBP>%s</DBP>" +
                "<MBP>%s</MBP>" +
                "<Left_SBP>%s</Left_SBP>" +
                "<Left_DBP>%s</Left_DBP>" +
                "<Left_MBP>%s</Left_MBP>" +
                "<Right_SBP>%s</Right_SBP>" +
                "<Right_DBP>%s</Right_DBP>" +
                "<Right_MBP>%s</Right_MBP>" +
                "<SPO2>%s</SPO2>" +
                "<PR>%s</PR>" +
                "<Glu>%s</Glu>" +
                "<Glu_style>%s</Glu_style>" +
                "<Height>%s</Height>" +
                "<Weight>%s</Weight>" +
                "<WAIST>%s</WAIST>" +
                "<Hipline>%s</Hipline>" +
                "<Temp>%s</Temp>" +
                "<Urine_ph>%s</Urine_ph>" +
                "<Urine_ubg>%s</Urine_ubg>" +
                "<Urine_bld>%s</Urine_bld>" +
                "<Urine_pro>%s</Urine_pro>" +
                "<Urine_ket>%s</Urine_ket>" +
                "<Urine_nit>%s</Urine_nit>" +
                "<Urine_glu>%s</Urine_glu>" +
                "<Urine_bil>%s</Urine_bil>" +
                "<Urine_leu>%s</Urine_leu>" +
                "<Urine_sg>%s</Urine_sg>" +
                "<Urine_vc>%s</Urine_vc>" +
                "<Urine_cre>%s</Urine_cre>" +
                "<Urine_ca>%s</Urine_ca>" +
                "<Anal>%s</Anal>" +
                "<BMI/>" +
                "<ASSKFXTL/>" +
                "<ASSXHDB>%s</ASSXHDB>" +
                "<ASSHXBYJZ>%s</ASSHXBYJZ>" +
                "<ASSBXB>%s</ASSBXB>" +
                "<ASSXXB/>" +
                "<ASSKFXTDL/>" +
                "<ASSWLDB>%s</ASSWLDB>" +
                "<ASSTHXHDB/>" +
                "<GGNXQGB/>" +
                "<GGNXQGC/>" +
                "<GGNBDB/>" +
                "<GGNZDHS/>" +
                "<SGNXQJ/>" +
                "<SGNXNSD/>" +
                "<SGNXJND/>" +
                "<SGNXNND/>" +
                "<URICACID>%S</URICACID>" +
                "<XZZDGC>%s</XZZDGC>" +
                "<XZGYSZ/>" +
                "<XZGQD/>" +
                "<WaveForm>" +
                "<Sample>%s</Sample>" +
                "<P05>%s</P05>" +
                "<N05>%s</N05>" +
                "<Duration>%s</Duration>" +
                "<ECG_I>%s</ECG_I>" +
                "<ECG_II>%s</ECG_II>" +
                "<ECG_III>%s</ECG_III>" +
                "<ECG_aVR>%s</ECG_aVR>" +
                "<ECG_aVF>%s</ECG_aVF>" +
                "<ECG_aVL>%s</ECG_aVL>" +
                "<ECG_V1>%s</ECG_V1>" +
                "<ECG_V2>%s</ECG_V2>" +
                "<ECG_V3>%s</ECG_V3>" +
                "<ECG_V4>%s</ECG_V4>" +
                "<ECG_V5>%s</ECG_V5>" +
                "<ECG_V6>%s</ECG_V6>" +
                "</WaveForm>" +
                "<RESP_RR>%s</RESP_RR>" +
                "<province>%s</province>" +
                "<city>%s</city>" +
                "<county>%s</county>" +
                "<address>%s</address>" +
                "</TAIO_HEACHECK>";
        return str;
    }

    /**
     * 尿常规值转换
     * @param value 模块传递过来的值
     * @return 显示测量值
     */
    public static String valueToString(int value) {

        switch (value) {
            case -1:
                return "-";
            case 0:
                return "+-";
            case 1:
                return "+1";
            case 2:
                return "+2";
            case 3:
                return "+3";
            case 4:
                return "+4";
            case 5:
                return "+";
            case 6:
                return "Normal";
            default:
                return String.valueOf(value);
        }
    }

    /**
     * 拼接上传字段的方法
     * @param bean 病人bean
     * @param context context
     * @param measure 测量数据bean
     * @return 拼接好的xml文件
     */
    public static String getXmlData(Context context, PatientBean bean, MeasureDataBean measure) {
        String icpName = ""; //检查机构名称
        String deviceID = ProviderReader.getDeviceCode(context); //一体机编号
        if (TextUtils.isEmpty(deviceID)) {
            deviceID = "M0000";
        }
        String name = bean.getName(); //姓名
        String sex = bean.getSex() + ""; //性别
        //生日 yyyy-MM-dd
        String birthday = UiUtils.getDateFormat(UiUtils.DateState.SHORT)
                .format(new Date(bean.getBirthday()));
        //检查时间yyyy-MM-dd hh:mm:ss
        String checkDate = UiUtils.getDateFormat(UiUtils.DateState.LONG)
                .format(new Date(measure.getMeasureTime()));
        //心率 次/分钟
        String hr = (measure.getTrendValue(KParamType.ECG_HR) == -1000) ? ""
                : String.valueOf(measure.getTrendValue(KParamType
                .ECG_HR) / GlobalConstant.INT_FACTOR);
        //收缩压 mmHg
        String sbp = (measure.getTrendValue(KParamType.NIBP_SYS) == -1000) ?
                "" : String.valueOf(measure.getTrendValue(KParamType
                .NIBP_SYS) / GlobalConstant.INT_FACTOR);
        //舒张压 mmHg
        String dbp = (measure.getTrendValue(KParamType.NIBP_DIA) == -1000) ?
                "" : String.valueOf(measure.getTrendValue(KParamType
                .NIBP_DIA) / GlobalConstant.INT_FACTOR);
        //平均压 mmHg
        String mbp = (measure.getTrendValue(KParamType.NIBP_MAP) == -1000) ?
                "" : String.valueOf(measure.getTrendValue(KParamType
                .NIBP_MAP) / GlobalConstant.INT_FACTOR);
        //血氧饱和度 %
        String spo2 = (measure.getTrendValue(KParamType.SPO2_TREND) ==
                -1000) ? "" : String.valueOf(measure.getTrendValue(KParamType.SPO2_TREND)
                / GlobalConstant.INT_FACTOR);
        //脉率 次/分钟
        String pr = (measure.getTrendValue(KParamType.SPO2_PR) == -1000) ? "" : String.
                valueOf(measure.getTrendValue(KParamType.SPO2_PR) / GlobalConstant.INT_FACTOR);
        //血糖 mmol/L
        String glu = (measure.getTrendValue(KParamType.BLOODGLU_BEFORE_MEAL)
                == -1000) ? "" : String.valueOf((float) measure
                .getTrendValue(KParamType.BLOODGLU_BEFORE_MEAL) /
                GlobalConstant.INT_FACTOR);
        //身高 cm
        String height = measure.getHeight() == GlobalConstant.INVALID_DATA ? "" :
                measure.getHeight() / GlobalConstant.FACTOR + "";
        //体重 kg
        String weight = measure.getWeight() == GlobalConstant.INVALID_DATA ? "" :
                measure.getWeight() / GlobalConstant.FACTOR + "";
        String leftSbp = ""; //左收缩压
        String leftDbp = ""; //左舒张压
        String leftMbp = ""; //左平均压
        String rightSbp = ""; //右收缩压
        String rightDbp = ""; //右舒张压
        String rightMbp = ""; //右平均压
        String gluStyle = parseGluType(measure.getGluStyle()); //血糖测量方式
        String waist = bean.getWaist() == null ? "" : bean.getWaist(); //腰围 cm
        String hipline = bean.getHipline() == null ? "" : bean.getHipline(); //臀围 cm
        //体温 摄氏度
        String temp = "";
        temp = (measure.getTrendValue(KParamType
                .IRTEMP_TREND) == -1000) ? "" : String
                .valueOf(measure.getTrendValue(KParamType.IRTEMP_TREND) / GlobalConstant.FACTOR);
        //体质指数
        double bmi = bean.getWeight() / ((bean.getHeight() / 100) *
                (bean.getHeight() / GlobalConstant.INT_FACTOR));
        //血常规--血红蛋白 (g/L)
        String assxhdb = (measure.getTrendValue(KParamType.BLOOD_HGB) ==
                -1000) ? "" : String.valueOf((float) measure
                .getTrendValue(KParamType.BLOOD_HGB) / GlobalConstant
                .INT_FACTOR);
        //血氧饱和度%
        String asshxbyjz = (measure.getTrendValue(KParamType.BLOOD_HCT) ==
                -1000) ? "" : String.valueOf(measure.getTrendValue(KParamType.BLOOD_HCT)
                / GlobalConstant.INT_FACTOR);
        //血常规--白细胞
        String assbxb = (measure.getTrendValue(KParamType.BLOOD_WBC) ==
                -1000) ? "" : String.valueOf((float) measure
                .getTrendValue(KParamType.BLOOD_WBC) / 100000);
        //尿常规酸碱度
        String urinePh = (measure.getTrendValue(KParamType.URINERT_PH) ==
                -1000) ? "" : String.valueOf((float) measure
                .getTrendValue(KParamType.URINERT_PH) / 100.0f);
        //尿常规尿胆原
        String urineUbg = (measure.getTrendValue(KParamType.URINERT_UBG) ==
                -1000) ? "" : DBDataUtil.valueToString(measure.getTrendValue(KParamType.URINERT_UBG)
                / GlobalConstant.INT_FACTOR);
        //尿常规隐血
        String urineBld = (measure.getTrendValue(KParamType.URINERT_BLD) ==
                -1000) ? "" : DBDataUtil.valueToString(measure.getTrendValue(KParamType.URINERT_BLD)
                / GlobalConstant.INT_FACTOR);
        //尿常规尿蛋白
        String urinePro = (measure.getTrendValue(KParamType.URINERT_PRO) ==
                -1000) ? "" : DBDataUtil.valueToString(measure.getTrendValue(KParamType.URINERT_PRO)
                / GlobalConstant.INT_FACTOR);
        //尿常规酮体
        String urineKet = (measure.getTrendValue(KParamType.URINERT_KET) ==
                -1000) ? "" : DBDataUtil.valueToString(measure.getTrendValue(KParamType.URINERT_KET)
                / GlobalConstant.INT_FACTOR);
        //尿常规亚硝酸盐
        String urineNit = (measure.getTrendValue(KParamType.URINERT_NIT) ==
                -1000) ? "" : DBDataUtil.valueToString(measure.getTrendValue(KParamType.URINERT_NIT)
                / GlobalConstant.INT_FACTOR);
        //尿常规尿糖
        String urineGlu = (measure.getTrendValue(KParamType.URINERT_GLU) ==
                -1000) ? "" : DBDataUtil.valueToString(measure.getTrendValue(KParamType.URINERT_GLU)
                / GlobalConstant.INT_FACTOR);
        //尿常规胆红素
        String urineBil = (measure.getTrendValue(KParamType.URINERT_BIL) ==
                -1000) ? "" : DBDataUtil.valueToString(measure.getTrendValue(KParamType.URINERT_BIL)
                / GlobalConstant.INT_FACTOR);
        //尿常规白细胞
        String urineLeu = (measure.getTrendValue(KParamType.URINERT_LEU) ==
                -1000) ? "" : DBDataUtil.valueToString(measure.getTrendValue(KParamType.URINERT_LEU)
                / GlobalConstant.INT_FACTOR);
        //尿常规尿比密
        String urineSg = (measure.getTrendValue(KParamType.URINERT_SG) ==
                -1000) ? "" : String.format(Locale.ENGLISH, "%.3f", (double) measure
                .getTrendValue(KParamType.URINERT_SG) / 1000.0f);
        //尿常规维生素c
        String urineAsc = (measure.getTrendValue(KParamType.URINERT_ASC) ==
                -1000) ? "" : DBDataUtil.valueToString(measure.getTrendValue(KParamType.URINERT_ASC)
                / GlobalConstant.INT_FACTOR);
        //肌酐（mmol/L）
        String urineCre = (measure.getTrendValue(KParamType.URINERT_CRE) ==
                -1000) ? "" : String.format(Locale.ENGLISH, "%.1f", (float) measure
                .getTrendValue(KParamType.URINERT_CRE) / GlobalConstant
                .INT_FACTOR);
        //尿钙（mmol/L）
        String urineCa = (measure.getTrendValue(KParamType.URINERT_CA) ==
                -1000) ? "" : String.valueOf((float) measure
                .getTrendValue(KParamType.URINERT_CA) / GlobalConstant
                .INT_FACTOR);
        //尿微量白蛋白  （mg/dL）
        String asswldb = (measure.getTrendValue(KParamType.URINERT_ALB) ==
                -1000) ? "" : String.valueOf(measure.getTrendValue(KParamType.URINERT_ALB)
                / GlobalConstant.INT_FACTOR);
        //尿酸 (mmol/L)
        String uricacid = (measure.getTrendValue(KParamType.URICACID_TREND)
                == -1000) ? "" : String.valueOf((float) measure
                .getTrendValue(KParamType.URICACID_TREND) / 100);
        //血脂--总胆固醇  (mmol/L)
        String xzzdgc = (measure.getTrendValue(KParamType.CHOLESTEROL_TREND)
                == -1000) ? "" : String.valueOf((float) measure
                .getTrendValue(KParamType.CHOLESTEROL_TREND) / 100);
        //心电图自动诊断结果
        String anal = measure.getEcgDiagnoseResult();
        String sample = "500"; //波形采样率
        String p05 = "2150"; //+5
        String n05 = "1946"; //-5
        String duration = "5"; //现在为5秒
        //心电图波形图数据
        String ecgI = Base64.encodeToString(UnitConvertUtil
                .getByteformHexString(measure.getEcgWave(KParamType.ECG_I)), Base64.NO_WRAP);
        String ecgIi = Base64.encodeToString(UnitConvertUtil
                .getByteformHexString(measure.getEcgWave(KParamType.ECG_II)), Base64.NO_WRAP);
        String ecgIii = Base64.encodeToString(UnitConvertUtil
                .getByteformHexString(measure.getEcgWave(KParamType.ECG_III)), Base64.NO_WRAP);
        String ecgAvr = Base64.encodeToString(UnitConvertUtil
                .getByteformHexString(measure.getEcgWave(KParamType.ECG_AVR)), Base64.NO_WRAP);
        String ecgAvf = Base64.encodeToString(UnitConvertUtil
                .getByteformHexString(measure.getEcgWave(KParamType.ECG_AVF)), Base64.NO_WRAP);
        String ecgAvl = Base64.encodeToString(UnitConvertUtil
                .getByteformHexString(measure.getEcgWave(KParamType.ECG_AVL)), Base64.NO_WRAP);
        String ecgV1 = Base64.encodeToString(UnitConvertUtil
                .getByteformHexString(measure.getEcgWave(KParamType.ECG_V1)), Base64.NO_WRAP);
        String ecgV2 = Base64.encodeToString(UnitConvertUtil
                .getByteformHexString(measure.getEcgWave(KParamType.ECG_V2)), Base64.NO_WRAP);
        String ecgV3 = Base64.encodeToString(UnitConvertUtil
                .getByteformHexString(measure.getEcgWave(KParamType.ECG_V3)), Base64.NO_WRAP);
        String ecgV4 = Base64.encodeToString(UnitConvertUtil
                .getByteformHexString(measure.getEcgWave(KParamType.ECG_V4)), Base64.NO_WRAP);
        String ecgV5 = Base64.encodeToString(UnitConvertUtil
                .getByteformHexString(measure.getEcgWave(KParamType.ECG_V5)), Base64.NO_WRAP);
        String ecgV6 = Base64.encodeToString(UnitConvertUtil
                .getByteformHexString(measure.getEcgWave(KParamType.ECG_V6)), Base64.NO_WRAP);
        String respRr = (measure.getTrendValue(KParamType.RESP_RR) ==
                -1000) ? "" : String.valueOf((float) measure
                .getTrendValue(KParamType.RESP_RR) / 10000);
        String single = "konsung"; //事先固定好的一个私钥
        String equipmentModel = UiUtils.getAreaName() + "-1"; //设备类型
        String area = UiUtils.getAreaName(); //设备地区
        String uploadDate = UiUtils.getDateFormat(UiUtils.DateState.LONG)
                .format(new Date()); //上传时间
        //加密字段，key=md5(uploadDate+area+single),其中single是在事先固定好的一个私钥。
        String key = UiUtils.stringMD5(uploadDate + area + single);
        String id = measure.getUuid();
        String doctor = ""; //以上名字
        String province = ""; //省编码
        String city = ""; //城市编码
        String county = ""; //地区编码
        String address = ""; //详细地址
        //获取模板xml
        String str = DBDataUtil.getUpLoadXml();
        String strArg4 = String.format(str, id, uploadDate, area,
                equipmentModel, key, icpName, deviceID, bean.getIdcard(),
                name, sex, birthday, doctor, checkDate,
                hr, sbp, dbp, mbp, leftSbp, leftDbp, leftMbp,
                rightSbp, rightDbp, rightMbp, spo2, pr, glu, gluStyle, height,
                weight, waist, hipline, temp,
                urinePh, urineUbg, urineBld,
                urinePro, urineKet, urineNit, urineGlu,
                urineBil, urineLeu,
                urineSg, urineAsc, urineCre, urineCa, anal,
                assxhdb, asshxbyjz, assbxb,
                asswldb, uricacid, xzzdgc, sample, p05, n05, duration,
                ecgI, ecgIi, ecgIii, ecgAvr, ecgAvf, ecgAvl,
                ecgV1, ecgV2, ecgV3, ecgV4, ecgV5, ecgV6,
                respRr, province, city, county, address);
        return strArg4;
    }

    /**
     * 转换血糖类型，与服务器对应
     * 0 - 0 餐前血糖
     * 1 - 2 餐后血糖
     * @param gluType 血糖类型
     * @return 转换血糖类型
     */
    public static String parseGluType(String gluType) {
        if (!TextUtils.isEmpty(gluType) && gluType.equals("1")) {
            return "2";
        }
        return "0";
    }

    /**
     * 判断用户是否所有数据上传
     * @param context 上下文引用
     * @param idCard 身份证
     * @return 是否所有测量数据已经上传
     */
    public static boolean isUploadAll(Context context, String idCard) {
        boolean uploadAll = false;
        List<MeasureDataBean> measureDataBeanList = GreenDaoManager.getMeasureDao(context)
                .queryBuilder().where(MeasureDataBeanDao.Properties.Idcard.eq(idCard)).list();
        if (null != measureDataBeanList && measureDataBeanList.size() > 0) {
            for (int i = 0; i < measureDataBeanList.size(); i++) {
                MeasureDataBean bean = measureDataBeanList.get(i);
                if (!bean.getUploadFlag()) {
                    uploadAll = false;
                    break;
                }
                uploadAll = true;
            }
        }
        return uploadAll;
    }

    /**
     * 更新用户数据是否全部上传状态
     * @param idCard 身份证号
     * @param context 上下文引用
     */
    public static void updatePatientUploadState(Context context, String idCard) {
        PatientBeanDao patientBeanDao = GreenDaoManager.getPatientDao(context);
        List<PatientBean> patientList = patientBeanDao.queryBuilder()
                .where(PatientBeanDao.Properties.Idcard.eq(idCard)).list();
        if (null != patientList && patientList.size() > 0) {
            PatientBean patient = patientList.get(0);
            patient.setIsUploadAll(isUploadAll(context, idCard));
            patientBeanDao.update(patient);
        }
    }

    /**
     * 根据条件查询数据
     * @param context 上下文引用
     * @param start 开始的条数
     * @param count 查询多少条
     * @param condition 查询条件
     * @return 查询的数据
     */
    public static List<PatientBean> getPatientBeen(Context context
            , int start, int count, String condition) {
        PatientBeanDao patientDao = GreenDaoManager.getPatientDao(context);
        QueryBuilder<PatientBean> patientQb = patientDao.queryBuilder();
        if (!TextUtils.isEmpty(condition)) {
            patientQb.whereOr(PatientBeanDao.Properties.Name.like("%" + condition + "%"),
                    PatientBeanDao.Properties.Idcard.like("%" + condition + "%")).list();
        }
        patientQb.offset(start);
        patientQb.limit(count);
        patientQb.orderDesc(PatientBeanDao.Properties.AddDate);
        //查询数据去重
        patientQb.distinct();
        return patientQb.list();
    }

    /**
     * 根据条件查询一共多少条数据
     * @param context 上下文 引用
     * @return 查询的数据条数
     */
    public static long getPatients(Context context) {
        PatientBeanDao patientDao = GreenDaoManager.getPatientDao(context);
        QueryBuilder<PatientBean> patientQb = patientDao.queryBuilder();
        //数据去重
        patientQb.distinct();
        return patientQb.count();
    }
}
